<?php
/**
 * DES 加密算法<p/>
 * 如果使用过程中出现报错，查看php.ini配置文件有没有打开extension=php_mcrypt.dll模块
 *
 * @catepory 加密解密
 * @author zhouhaichao(a)2008.sina.com
 * @version 1.0
 * @copyright (c) 2008
 * @date 2013-2-18
 * <code>
 * $new = encrypt(“wo shi old”,”111″);
 * $old = decrypt($new,”111″);
 * echo $new.”的明文是：”.”<br>”;
 * echo $old;
 * </code>
 */

define('DEFAULT_KEY', 'KEY.LCYR');//定义默认加密钥匙

/**
 * 加密函数：encrypt
 * @param encrypt 需要加密的字符
 * @param key 加密钥匙,默认为空
 */
function encrypt($txt, $key = DEFAULT_KEY)
{
    srand((double)microtime() * 1000000);
    $encrypt_key = md5(rand(0, 32000));
    $ctr = 0;
    $tmp = '';
    for ($i = 0; $i < strlen($txt); $i++) {
        $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
        $tmp .= $encrypt_key[$ctr] . ($txt[$i] ^ $encrypt_key[$ctr++]);
    }
    return base64_encode(passport_key($tmp, $key));
}

/**
 * 解密方法:decrypt
 * @param string decrypt 需要解密字符
 * @param string key 解密钥匙，默认为空，
 */
function decrypt($txt, $key = DEFAULT_KEY)
{
    $txt = passport_key(base64_decode($txt), $key);
    $tmp = '';
    for ($i = 0; $i < strlen($txt); $i++) {
        $md5 = $txt[$i];
        $tmp .= $txt[++$i] ^ $md5;
    }
    return $tmp;
}

function passport_key($txt, $encrypt_key)
{
    $encrypt_key = md5($encrypt_key);
    $ctr = 0;
    $tmp = '';
    for ($i = 0; $i < strlen($txt); $i++) {
        $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
        $tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
    }
    return $tmp;
}
